package com.ycy.chuwenuniapp.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycy.chuwenuniapp.common.ResCodeEnum;
import com.ycy.chuwenuniapp.common.ResData;
import com.ycy.chuwenuniapp.entity.AdminKey;
import com.ycy.chuwenuniapp.entity.User;
import com.ycy.chuwenuniapp.exception.CustomException;
import com.ycy.chuwenuniapp.mapper.IAdminKeyMapper;
import com.ycy.chuwenuniapp.mapper.IUserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminKeyService extends ServiceImpl<IAdminKeyMapper, AdminKey> {
    @Resource
    private UserService userService;

    //增加或修改
    public ResData<Boolean> saveAdminKey(AdminKey entity) {
        String secretKey = entity.getSecretKey();
        if(StrUtil.isBlank(secretKey)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"缺失secretKey");

        return ResData.success(saveOrUpdate(entity));
    }

    //查全部
    public ResData<Boolean> checkKey(String secretKey,String userId) {
        if(StrUtil.isBlank(secretKey)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"缺失secretKey");
        List<AdminKey> list = list();
        if(list.size() > 1) throw new CustomException(ResCodeEnum.SERVER_ERROR,"错误的存在多个adminKey");
        else if(list.size() == 0) throw new CustomException(ResCodeEnum.SERVER_ERROR,"错误的不存在adminKey");
        if(secretKey.equals(list.get(0).getSecretKey())) {
            //验证通过后，需要将角色变更为管理员
            Boolean isUpdateAdminFlag = userService.updateAdminFlag(userId);
            if(!isUpdateAdminFlag) throw new CustomException(ResCodeEnum.SERVER_ERROR,"验证通过，但更新为管理员时错误");
            return ResData.success(true,"验证成功");
        }
        else return ResData.success(false,"秘钥错误");
    }
}
